﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Marmat.Foundation;
using Marmat.FrameWork;

namespace Marmat.Template.WinForm
{
    /// <summary>
    /// 菜单管理实例
    /// </summary>
    public class MeunManagement : IMeunManagement
    {
        private readonly Dictionary<IMenu, IMenuItemBuilder> collection = new Dictionary<IMenu, IMenuItemBuilder>();

        /// <summary>
        /// 返回一个循环访问集合的枚举器。
        /// </summary>
        /// <returns>用于循环访问集合的枚举数。</returns>
        public virtual IEnumerator<IMenu> GetEnumerator()
        {
            List<IMenu> menus = new List<IMenu>();
            IEnumerable<IMenuItemBuilder> menuItemBuilders = SystemCommand.GetServices<IMenuItemBuilder>();
            foreach (IMenuItemBuilder item in menuItemBuilders)
            {
                IMenu[] tmp = menus.ToArray(); //备份之前的菜单项
                item.Builder(menus);//执行菜单构建函数
                var addMenuCollection = menus.Where(x => !tmp.Contains(x)).ToList();//通过备份的菜单集合和现有的菜单集合对比，获取本次新增的菜单集合
                addMenuCollection.ForEach(x => collection.Add(x, item));//将新增的菜单集合绑定到对应的事件处理集合中。
            }

            if (menus.Count() > 0)
            {
                // 名称相同的菜单集合
                var repetitionCollection = menus.GroupBy(x => x.Name).Where(g => g.Count() > 1).Select(s => s.Key);
                // 名称与父节点名称相同的菜单集合
                var nodeNameSameCollection = menus.Where(x => x.Name == x.Parent).Select(s => s.Name);

                var topNodeCollection = menus.Where(x => string.IsNullOrEmpty(x.Parent));
                if (repetitionCollection.Count() > 0)
                {
                    throw new Exception(string.Join(",", repetitionCollection) + " 存在重复名称的菜单！");
                }
                else if (nodeNameSameCollection.Count() > 0)
                {
                    throw new Exception(string.Join(",", nodeNameSameCollection) + "菜单父节点不能与自身名称相同！");
                }
            }
            return menus.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        /// <summary>
        /// 点击菜单项时执行。
        /// </summary>
        /// <param name="menu">点击的菜单项</param>
        public virtual void ItemClick(IMenu menu)
        {
            if (collection.ContainsKey(menu))
                collection[menu].ItemClick(menu);
        }
    }
}
